package servlet.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.MerchantApplication;
import service.MerchantApplicationManager;
import service.factory.ManagerFactory;
import util.JsonUtil;
import dto.AdminMerchantDto;
import dto.ResponseDto;

/**
 * Servlet implementation class GetMerchantByStatusServlet
 */
public class GetMerchantByStatusServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantApplicationManager amanager = null;
       
    public GetMerchantByStatusServlet() {
        super();
        amanager = ManagerFactory.getApplicationManagerInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String status = request.getParameter("status");
		List<MerchantApplication> mList = new ArrayList<>();
		if(status==null||"".equals(status)){
			mList = amanager.getAll();
		}else {
			mList = amanager.getByStatus(status);
		}
		List<AdminMerchantDto> adminMerchantDtos = new ArrayList<>();
		String avatarPath = (String) getServletContext().getAttribute("imagepath");
		String idCardPath = getServletContext().getContextPath()+"/merchant/info/idcard?name=";
		for (MerchantApplication application : mList) {
			AdminMerchantDto adminMerchantDto = new AdminMerchantDto(application.getName(),idCardPath+application.getName(),
					avatarPath+application.getAvatar(),application.getAddress(),application.getStatus());
			adminMerchantDtos.add(adminMerchantDto);
		}
		ResponseDto responseDto = new ResponseDto(1,"success",adminMerchantDtos);
		PrintWriter writer = response.getWriter();
		writer.write(JsonUtil.toJsonString(responseDto));
		writer.close();
	}
}
